package com.example;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;

//TIP 要<b>运行</b>代码，请按 <shortcut actionId="Run"/> 或
// 点击装订区域中的 <icon src="AllIcons.Actions.Execute"/> 图标。
public class Main {
    public static void main(String[] args) {
        HashMap<String, Object> map = new HashMap<>();

        Calendar instance = Calendar.getInstance();
        // 20秒后令牌token失效
        instance.add(Calendar.SECOND, 20);

        String token = JWT.create()
                .withHeader(map) // header可以不写，因为默认值就是它
                .withClaim("userId", 1)  //payload
                .withClaim("username", "admin")
                .withExpiresAt(instance.getTime()) // 指定令牌的过期时间
                .sign(Algorithm.HMAC256("EXAMPLE"));//签名
        System.out.println(token);

        System.out.println("------------------------------------------------------------------------");


        // 通过签名生成验证对象
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("EXAMPLE")).build();
        DecodedJWT verify = jwtVerifier.verify(token);
        System.out.println(verify.getClaim("userId"));
        System.out.println(verify.getClaim("username"));
        System.out.println("令牌过期时间："+verify.getExpiresAt());

        System.out.println("------------------------------------------------------------------------");

        //- SignatureVerificationException   签名不一致异常
        //- TokenExpiredException            令牌过期异常
        //- AlgorithmMismatchException       算法不匹配异常
        //- InvalidClaimException            失效的payload异常
        try{
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
        }
        catch (SignatureVerificationException e){
            e.printStackTrace();
            System.out.println("签名不一致异常");
        }
        catch (TokenExpiredException e){
            e.printStackTrace();
            System.out.println("令牌过期异常");
        }
        catch (AlgorithmMismatchException e){
            e.printStackTrace();
            System.out.println("算法不匹配异常");
        }
        catch (InvalidClaimException e){
            e.printStackTrace();
            System.out.println("失效的payload异常");
        }
        catch (Exception e){
            e.printStackTrace();
            System.out.println("其他异常");
        }
    }
}